package com.lintf.wxpay.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.lintf.business.entity.OrderInfo;
import com.lintf.business.entity.RefundInfo;
import com.lintf.wxpay.base.utils.OrderNoUtils;
import com.lintf.wxpay.mapper.RefundInfoMapper;
import com.lintf.wxpay.service.OrderInfoService;
import com.lintf.wxpay.service.RefundInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lintf
 * @description 针对表【refund_info】的数据库操作Service实现
 * @createDate 2024-11-22 09:12:32
 */
@Service
public class RefundInfoServiceImpl extends ServiceImpl<RefundInfoMapper, RefundInfo>
        implements RefundInfoService {

    @Autowired
    private OrderInfoService orderInfoService;

    @Override
    public RefundInfo createRefundInfoByOrderNo(String orderNo, String reason) {
        LambdaUpdateWrapper<OrderInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderInfo::getOrderNo, orderNo);
        OrderInfo orderInfo = orderInfoService.getOne(wrapper);
        RefundInfo refundInfo = new RefundInfo();
        refundInfo.setOrderNo(orderNo)
                .setRefundNo(OrderNoUtils.getRefundNo())
                .setTotalFee(orderInfo.getTotalFee())
                .setRefund(orderInfo.getTotalFee())
                .setReason(reason);
        baseMapper.insert(refundInfo);
        return refundInfo;
    }

    @Override
    public void updateRefund(String bodyAsString) {
        Gson gson = new Gson();
        Map<String, String> resultMap = gson.fromJson(bodyAsString, HashMap.class);

        LambdaQueryWrapper<RefundInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RefundInfo::getRefundNo, resultMap.get("out_refund_no"));

        RefundInfo refundInfo = new RefundInfo();
        refundInfo.setRefundId(resultMap.get("refund_id"));

        // 查询退款和申请退款中的返回参数
        if (resultMap.get("status") != null) {
            refundInfo.setRefundStatus(resultMap.get("status"));
            // 将响应结果存入数据库
            refundInfo.setContentReturn(bodyAsString);
        }

        // 退款回调中的回调参数
        if (resultMap.get("refund_status") != null) {
            refundInfo.setRefundStatus(resultMap.get("refund_status"));
            // 将响应结果存入数据库
            refundInfo.setContentNotify(bodyAsString);
        }
        baseMapper.update(refundInfo, wrapper);
    }
}




